//
//  AppDelegate.m
//  JKRecover
//
//  Created by Veer on 2018/5/30.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "AppDelegate.h"

#import "XMGTabBarController.h"
#import "XMGNavigationController.h"
#import "VRFirefightingViewController.h"
#import "VRAlarmViewController.h"
#import "VRMeViewController.h"
#import "VRLoginViewController.h"

@interface AppDelegate ()

@property (nonatomic, strong) XMGTabBarController *homeVC;

@property (nonatomic, assign) AFNetworkReachabilityStatus lastNetworkStatus;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.lastNetworkStatus = 100;
    
    // 设置SVProgressHUD 的样式
    [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6]];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD setMinimumSize:CGSizeMake(60, 0)];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setMinimumDismissTimeInterval:1.0];
    
    // 处理键盘遮挡
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
//    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    XMGTabBarController *rootVC = [XMGTabBarController tabBarControllerWithAddChildVCsBlock:^(XMGTabBarController *tabBarC) {
        [tabBarC addChildVC:[VRFirefightingViewController new] title:@"智慧消防" normalImageName:@"intelligent_fire" selectedImageName:@"intelligent_fire1" isRequiredNavController:YES];
        [tabBarC addChildVC:[VRAlarmViewController new] title:@"报警" normalImageName:@"alert" selectedImageName:@"alert1" isRequiredNavController:YES];
        [tabBarC addChildVC:[VRMeViewController new] title:@"我的" normalImageName:@"mine" selectedImageName:@"mine1" isRequiredNavController:YES];
    }];
    self.homeVC = rootVC;
    
    [NSThread sleepForTimeInterval:3.0];
    [self startToListenNow];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:kLoginSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logout) name:kLogout object:nil];
    
//    self.window.rootViewController = rootVC;
    
//    [self.window makeKeyAndVisible];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (void)loginSuccess
{
    
    if ([UIApplication sharedApplication].keyWindow.rootViewController.presentedViewController) {
        [[UIApplication sharedApplication].keyWindow.rootViewController.presentedViewController dismissViewControllerAnimated:YES completion:nil];
    }else{
        self.window.rootViewController = self.homeVC;
    }
    
//    XMGNavigationController *nav = [[XMGNavigationController alloc] initWithRootViewController:[[VRLoginViewController alloc] init]];
//    self.window.rootViewController = nav;
}

- (void)logout
{
    XMGNavigationController *nav = [[XMGNavigationController alloc] initWithRootViewController:[[VRLoginViewController alloc] init]];
//    self.window.rootViewController = nav;
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:nav animated:YES completion:nil];
}


#pragma mark - networking
//网络监听
-(void)startToListenNow
{
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    weakify(self)
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        strongify(self)
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                NSLog(@"------NetworkReachability-----:AFNetworkReachabilityStatusReachableViaWWAN");
                [self tryToLoad];
                if (self.lastNetworkStatus == AFNetworkReachabilityStatusNotReachable || self.lastNetworkStatus == AFNetworkReachabilityStatusUnknown) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNetworkChanged object:@(AFNetworkReachabilityStatusReachableViaWWAN)];
                }
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                NSLog(@"------NetworkReachability-----:AFNetworkReachabilityStatusReachableViaWiFi");
                [self tryToLoad];
                if (self.lastNetworkStatus == AFNetworkReachabilityStatusNotReachable || self.lastNetworkStatus == AFNetworkReachabilityStatusUnknown) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNetworkChanged object:@(AFNetworkReachabilityStatusReachableViaWWAN)];
                }
            }
                break;
            case AFNetworkReachabilityStatusNotReachable:
            {
                NSLog(@"------NetworkReachability-----:AFNetworkReachabilityStatusNotReachable");
                [self tryToLoad];
            }
                break;
            case AFNetworkReachabilityStatusUnknown:
            {
                NSLog(@"------NetworkReachability-----:AFNetworkReachabilityStatusUnknown");
                [self tryToLoad];
            }
                break;
            default:
                break;
        }
        self.lastNetworkStatus = status;
    }];
    //开始监听
    [manager startMonitoring];
}


//请求方式
-(void)tryToLoad {
    
    [self loadHomePage];
//    NSURL *url1 = [NSURL URLWithString:GetBaseUrl_url];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1];
//    request.timeoutInterval = 2.0;
//    request.HTTPMethod = @"get";
//
//    NSURLResponse *response;
//    NSError *error;
//    NSData *backData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//    if (error) {
//
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self loadHomePage];
//        });
//    }else{
//        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:backData options:NSJSONReadingMutableContainers error:nil];
//
//        NSLog(@"dic======%@",dict);
//        NSString *baseUrl = dict[@"data"][@"url"];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (baseUrl.length > 0) {
//                [JKUser shareUser].baseUrl = baseUrl;
//            }
//            [self loadHomePage];
//        });
//    }
}


- (void)loadHomePage
{

    if ([VRUser shareUser].token) {

        self.window.rootViewController = self.homeVC;
    }else{
    
        XMGNavigationController *nav = [[XMGNavigationController alloc] initWithRootViewController:[[VRLoginViewController alloc] init]];
        self.window.rootViewController = nav;
    }
    
    [self.window makeKeyAndVisible];
}


@end
